<?php
class ModelSaleRecharge extends Model {
	public function addRecharge($data) {
        for($i=1;$i<=$data['quantity']; $i++){
            $this->db->query("INSERT INTO " . DB_PREFIX . "recharge SET code = '" . $this->verificationCode(16) . "' , price = '" . $data['price'] . "' , status = '0', date_added = NOW()");
        }
	}


    public function SetRechargeSubscribe($recharge_id){
        $this->db->query("UPDATE " . DB_PREFIX . "recharge SET status = '2' WHERE recharge_id='".$recharge_id."'");
    }
    public function getRecharges($data = array()) {
        $sql = "SELECT i.*,c.firstname,c.lastname FROM " . DB_PREFIX . "recharge i LEFT JOIN " . DB_PREFIX . "customer c ON(i.customer_id=c.customer_id)";

        $sort_data = array(
            'code',
            'date_activation',
            'customer_id',
            'date_added',
            'status'
        );

        if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
            $sql .= " ORDER BY " . $data['sort'];
        } else {
            $sql .= " ORDER BY recharge_id";
        }

        if (isset($data['order']) && ($data['order'] == 'DESC')) {
            $sql .= " DESC";
        } else {
            $sql .= " ASC";
        }

        if (isset($data['start']) || isset($data['limit'])) {
            if ($data['start'] < 0) {
                $data['start'] = 0;
            }

            if ($data['limit'] < 1) {
                $data['limit'] = 20;
            }

            $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }

        $query = $this->db->query($sql);
        return $query->rows;
    }

	public function deleteRecharge($recharge_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "recharge WHERE recharge_id = '" . (int)$recharge_id . "'");
	}

    public function getTotalRecharges() {
        $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "recharge");

        return $query->row['total'];
    }
    public function verificationCode($leng) {
    $arr   = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
    shuffle($arr);
    $str = implode('', array_slice($arr, 0, $leng));
    return $str;
}
}
?>